rm(list=ls())
library(tidyverse)
library(readxl)

# Read pop mun by age
pop_mun_by_age <- read_rds(here::here("data","processed","citycharacteristics","pop_mun_by_age.rds"))


# Create Tiebout indicators
pop_mun_by_age <- pop_mun_by_age %>% 
  mutate(pop_children = mun_pop_0_4+mun_pop_5_9+mun_pop_10_14+mun_pop_15,
         pop_adult = mun_pop_total - pop_children) %>% 
  select(mun_code,mun_name,year,pop_adult)

# read micro-region table
table <- list.files(here::here("data","raw","IBGE"), pattern = "tab_mun_microregion", full.names = T)

mun_micro_table <- read_excel(table,
                              skip = 1,
                              col_names = c("micro_code","micro_name","mun_code","mun_name"),
                              col_types = c(rep("text",4))) %>% 
  select(-mun_name)

# Join microregions and pop
pop_mun_by_age <- pop_mun_by_age %>% 
  left_join(mun_micro_table, by = "mun_code") 

pop_mun_over16 <- pop_mun_by_age %>% 
  group_by(micro_code,year) %>% 
  mutate(pop_tot_micro = sum(pop_adult,na.rm=T),
         H_tiebout_micro = sum((pop_adult/pop_tot_micro)^2)) %>% 
  ungroup()

# gather and place H_tibetout_year as variable

h_tiebout_2000 <- pop_mun_over16 %>% 
  filter(year == 2000) %>% 
  select(mun_code,mun_name,
         H_tiebout_micro_2000 = H_tiebout_micro)

h_tiebout_2010 <- pop_mun_over16 %>% 
  filter(year == 2010) %>% 
  select(mun_code,mun_name,
         H_tiebout_micro_2010 = H_tiebout_micro)

h_tiebout <- h_tiebout_2000 %>% 
  full_join(h_tiebout_2010, by = c("mun_code","mun_name")) 

h_tiebout <- h_tiebout %>% 
  mutate(mun_code = str_sub(mun_code,1,-2))

# Save RDS
write_rds(h_tiebout, here::here("data","processed","citycharacteristics","h_tiebout.rds"))
